// hyb_yl/zhuanjiasubpages/pages/danganList/danganList.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    searching: false,
    showText: 'LOG日志',
    delayTimer: null,
    devicesList: [],
    openid: "",
    yonghuList: [{
      img: 'https://696d-image-ac66k-1302520890.tcb.qcloud.la/35ddb86ef392aa8eb6cce74eded144f.png?sign=50dfb958793d1a6ba566ad1613545ee3&t=1594982472',
      name: '基础档案',
      url: '/hyb_yl/userCommunicate/pages/preindex/sickinfo/index',
    },
    {
      img: 'https://696d-image-ac66k-1302520890.tcb.qcloud.la/52353a8bfbd4e7df409ea0bc188034f.png?sign=954723ee46d1adbe16a5c294e49095b4&t=1594982441',
      name: '电子病历',
      url: '/hyb_yl/mysubpages/pages/dianzibingli/dianzibingli' //复制一份
    },
    {
      img: 'https://696d-image-ac66k-1302520890.tcb.qcloud.la/31f0233f4b78ab7f8c653f5546d07d8.png?sign=b05bddeb66a76cc2667989153fd43d42&t=1594982531',
      name: '报告查看',
      url: '/hyb_yl/mysubpages/pages/tijainbaogaoList/tijainbaogaoList' //复制一份
    },
    {
      img: 'https://696d-image-ac66k-1302520890.tcb.qcloud.la/6bcf43d3b77608ac58f7b44ae2d2054.png?sign=479f6a175c3be8c50696f5af0560c431&t=1594982811',
      name: '其他报告',
      url: '/hyb_yl/zhuanjiasubpages/pages/qitaList/qitaList' //复制一份
    },
    {
      img: 'https://696d-image-ac66k-1302520890.tcb.qcloud.la/6bcf43d3b77608ac58f7b44ae2d2054.png?sign=479f6a175c3be8c50696f5af0560c431&t=1594982811',
      name: '患者随访',
      url:'/hyb_yl/huanzhe/pages/all_plan/all_plan'
      // url: '/hyb_yl/zhuanjiasubpages/pages/timeline/timeline' //复制一份
    },
    {
      img: 'https://696d-image-ac66k-1302520890.tcb.qcloud.la/06.png?sign=c5541eb56a4fa26ca2b1871904115236&t=1620542422',
      name: '血压监测',
      url: '/hyb_yl/zhuanjiasubpages/pages/bloodpressure_report/bloodpressure_report' //复制一份
    },
    {
      img: 'https://696d-image-ac66k-1302520890.tcb.qcloud.la/07.png?sign=5abd8fa93d5889151501f307da6b4128&t=1620542441',
      name: '血糖监测',
      url: '/hyb_yl/zhuanjiasubpages/pages/bloodsugar_report/bloodsugar_report' //复制一份
    },
    {
      img: 'https://696d-image-ac66k-1302520890.tcb.qcloud.la/09.png?sign=8dba2b641a1366d128ca88a728c45261&t=1620557340',
      name: '腕表数据',
      url: '/hyb_yl/pharmacy/pages/wristwatch/wristwatch' //复制一份
    },
    {
      img: 'https://696d-image-ac66k-1302520890.tcb.qcloud.la/09.png?sign=8dba2b641a1366d128ca88a728c45261&t=1620557340',
      name: '体温检测',
      url: '/hyb_yl/pharmacy/pages/temperature/temperature' //复制一份
    },
    {
      img: 'https://696d-image-ac66k-1302520890.tcb.qcloud.la/09.png?sign=8dba2b641a1366d128ca88a728c45261&t=1620557340',
      name: '心率检测',
      url: '/hyb_yl/pharmacy/pages/heart_rate_cont/heart_rate_cont' //复制一份
    },
    {
      img: 'https://696d-image-ac66k-1302520890.tcb.qcloud.la/09.png?sign=8dba2b641a1366d128ca88a728c45261&t=1620557340',
      name: '尿酸检测',
      url: '/hyb_yl/pharmacy/pages/uric_acid/uric_acid' //复制一份
    },
    {
      img: 'https://696d-image-ac66k-1302520890.tcb.qcloud.la/09.png?sign=8dba2b641a1366d128ca88a728c45261&t=1620557340',
      name: '胆固醇检测',
      url: '/hyb_yl/pharmacy/pages/cholesterol/cholesterol' //复制一份
    },
    {
      img: 'https://696d-image-ac66k-1302520890.tcb.qcloud.la/07.png?sign=5abd8fa93d5889151501f307da6b4128&t=1620542441',
      name: '设备管理',
      url: '/hyb_yl/pharmacy/pages/equipment/equipment' //复制一份
    }
    ],
  },
  goback: function (e) {
    
    var url = e.currentTarget.dataset.url
    
    var nametitle = e.currentTarget.dataset.nametitle
    var names = this.data.names
    this.setData({
      url: url
    })
    var that = this
    var doc = that.data.doc
    if (doc == 1) {
      if (nametitle == '基础档案') {
        wx.navigateTo({
          url: '/hyb_yl/zhuanjiasubpages/pages/jichudangan/jichudangan?openid=' + this.data.openid + '&zid=' + wx.getStorageSync('zid') + '&names=' + names
        })
      } else {
        wx.navigateTo({
          url: url + '?openid=' + this.data.openid + '&zid=' + wx.getStorageSync('zid') + '&names=' + names
        })
      }
    } else {
      if (url == '/hyb_yl/pharmacy/pages/temperature/temperature') {
        that.setData({
          url: url + '?j_id=' + that.data.j_id
        })
        wx.openBluetoothAdapter({
          success: function (res) {
            that.Search();
          },
          fail: function (res) {
            wx.showModal({
              title: '提示',
              content: "手机蓝牙未开启，仅可查看记录",
              success: function (con) {
                if (con.confirm) {
                  wx.navigateTo({
                    url: url + '?j_id=' + that.data.j_id,
                  })
                }
              }
            })
          }
        })
      } else if (url == '/hyb_yl/pharmacy/pages/heartrate/heartrate' || url == '/hyb_yl/pharmacy/pages/uric_acid/uric_acid' || url == '/hyb_yl/pharmacy/pages/cholesterol/cholesterol' ||  url == '/hyb_yl/zhuanjiasubpages/pages/bloodsugar_report/bloodsugar_report') {

        wx.openBluetoothAdapter({//调用微信小程序api 打开蓝牙适配器接口
          success: function (res) {
            console.log(res)
            wx.showToast({
              title: '初始化成功',
              icon: 'success',
              duration: 800
            })
            that.findBlues();//2.0
          },
          fail: function (res) {//如果手机上的蓝牙没有打开，可以提醒用户
            console.log(333)
            wx.showModal({
              title: '提示',
              content: "手机蓝牙未开启，仅可查看记录",
              success: function (con) {
                if (con.confirm) {
                  wx.navigateTo({
                    url: url + '?j_id=' + that.data.j_id,
                  })
                }
              }
            })
          }
        })
      } else {
        wx.navigateTo({
          url: url + '?openid=' + this.data.openid + '&zid=' + wx.getStorageSync('zid') + '&names=' + names + '&j_id=' + that.data.j_id + '&doc=' + that.data.doc + '&open=1'
        })
      }

    }

  },
  findBlues() {
    var that = this
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: false,
      interval: 0,
      success: function (res) {
        console.log(res);
        wx.showLoading({
          title: '正在搜索设备',
        })
        that.getBlue()//3.0
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  getBlue() {
    var that = this
    var url = that.data.url;
    var type = '';
    if (url == '/hyb_yl/pharmacy/pages/uric_acid/uric_acid') {
      type = 'UA';
    } else if (url == '/hyb_yl/pharmacy/pages/cholesterol/cholesterol') {
      type = 'CHOL';
    } else if (url == '/hyb_yl/zhuanjiasubpages/pages/bloodsugar_report/bloodsugar_report') {
      type = 'GLU';
    }
    wx.getBluetoothDevices({
      success: function (res) {
        console.log(res)
        wx.hideLoading();
        for (var i = 0; i < res.devices.length; i++) {
          //that.data.inputValue：表示的是需要连接的蓝牙设备ID，简单点来说就是我想要连接这个蓝牙设备，所以我去遍历我搜索到的蓝牙设备中是否有这个ID
          if (res.devices[i].name.indexOf('PM10') > -1 || res.devices[i].localName.indexOf('PM10') > -1 || res.devices[i].name.indexOf('Device') > -1 || res.devices[i].localName.indexOf('Device') > -1) {
            that.setData({
              deviceId: res.devices[i].deviceId,
              consoleLog: "设备：" + res.devices[i].deviceId,
            })
            
            wx.redirectTo({ url: '/hyb_yl/pharmacy/pages/thermometer/index?connectedDeviceId=' + res.devices[i].deviceId + '&name=' + res.devices[i].name + '&j_id=' + that.data.j_id + '&type=' + type });
            return;
          }
        }
      },
      fail: function () {
        console.log("搜索蓝牙设备失败")
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;

    var openid = options.openid;
    var titlme = options.titlme;
    if (options.doc !== '0') {

      var nerlsit = {
        img: 'https://696d-image-ac66k-1302520890.tcb.qcloud.la/6bcf43d3b77608ac58f7b44ae2d2054.png?sign=479f6a175c3be8c50696f5af0560c431&t=1594982811',
        name: '开处方',
        url: '/hyb_yl/zhuanjiasubpages/pages/chufangmobo/chufangmobo' //复制一份
      }
      that.data.yonghuList.push(nerlsit)
      that.setData({
        doc: options.doc,
        yonghuList: that.data.yonghuList
      })
    } else {
      var nerlsit = {
        img: 'https://696d-image-ac66k-1302520890.tcb.qcloud.la/6bcf43d3b77608ac58f7b44ae2d2054.png?sign=479f6a175c3be8c50696f5af0560c431&t=1594982811',
        name: '查看处方',
        url: '/hyb_yl/zhuanjiasubpages/pages/chufangmobouser/chufangmobouser' //复制一份
      }
      that.data.yonghuList.push(nerlsit)
      that.setData({
        doc: options.doc,
        yonghuList: that.data.yonghuList
      })
    }
    wx.setNavigationBarTitle({
      title: titlme + '的档案'
    })
    that.setData({
      openid: openid,
      names: titlme,
      type: options.type,
      j_id: options.j_id,
    })
  },

  // 蓝牙设备检测数据体温心电
  Search() {
    var that = this;
    wx.startBluetoothDevicesDiscovery({
      success(res) {
        wx.showLoading({
          title: '正在搜索设备...',
        });

        var delayTimer = setInterval(function () {
          console.log('sousuo');
          that.findBlue();
        }, 2000);
        that.setData({
          delayTimer: delayTimer
        })
      },
      fail() {
        that.setData({
          showText: "搜索设备失败"
        })
        that.closeFindBlue();
      }
    })

  },
  findBlue() {
    var that = this;
    console.log('搜索开始')
    wx.getBluetoothDevices({
      success: function (res) {
        console.log('搜索成功')
        console.log(res)
        var deviceNum = 0;
        if (res.devices && (deviceNum = res.devices.length) >= 1) {
          that.setData({
            showText: "搜索设备数量：" + deviceNum
          })

          that.setData({
            devicesList: []

          });

          var biolandDevice;
          for (var i = 0; i < deviceNum; i++) {
            var device = res.devices[i];
            var deviceName = device.name;
            if (deviceName == null || deviceName == '')
              continue;

            var rssi = device.RSSI;
            if (deviceName.indexOf('Bioland-IT') > -1) {
              biolandDevice = device;
              var name = "devicesList[" + i + "].name";
              that.setData({
                [name]: deviceName
              });
              break;
            } else if (deviceName.indexOf('PM10') > -1) {
              biolandDevice = device;
              var name = "devicesList[" + i + "].name";
              that.setData({
                [name]: deviceName
              });
              break;
            } else if (deviceName.indexOf('BLE') > -1) {
              biolandDevice = device;
              var name = "devicesList[" + i + "].name";
              that.setData({
                [name]: deviceName
              });
              break;
            }
          }
          console.log(biolandDevice)
          if (biolandDevice != null) {
            wx.hideLoading();
            that.closeFindBlue();
            that.Connect(biolandDevice);
          }

        }
      }
    })
  },
  closeFindBlue() {
    var that = this;
    clearInterval(that.data.delayTimer);
    wx.stopBluetoothDevicesDiscovery({
      success: function (res) {
      }
    })
  },
  Connect(data) {
    if (data == null)
      return;
    var that = this
    wx.showLoading({
      title: '连接设备中...',
    })
    wx.createBLEConnection({
      deviceId: data.deviceId,
      success: function (res) {
        wx.hideLoading()
        console.log(that.data.j_id);

        wx.redirectTo({ url: '/hyb_yl/pharmacy/pages/thermometer/index?connectedDeviceId=' + data.deviceId + '&name=' + data.name + '&j_id=' + that.data.j_id + '&type=tem' });
      },
      fail: function (res) {
        wx.hideLoading()
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})